package com.xsg.printer.core.toolkit;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import lombok.SneakyThrows;
import java.io.*;
import java.nio.file.Files;
import java.util.List;

public class FileWriterUtils {

    private static final Logger logger = LoggerFactory.getLogger(FileWriterUtils.class);

    /**
     * 清理文件
     * @param path
     * @return
     */
    public static void clearFile (String path) {
        if (path == null) {
            return;
        }
        File file = new File(path);
        clearFile(file);
    }

    /**
     * 清理文件
     * @param paths
     */
    public static void clearFiles (List<String> paths) {
        if (paths == null || paths.isEmpty()) {
            return;
        }
        for (String path : paths) {
            clearFile(path);
        }
    }

    /**
     * 清空文件
     * @param file
     */
    public static void clearFile(File file) {
        if (file == null || !file.exists()) {
            return;
        }
        if (file.isFile() || file.list() == null) {
            try {
                Files.delete(file.toPath());
            } catch (IOException e) {
                logger.error("清空文件失败 ->{}, e->{}", file.getName(), e);
            }
        } else {
            for (File f : file.listFiles()) {
                clearFile(f);
            }
            try {
                Files.delete(file.toPath());
            } catch (IOException e) {
                logger.error("清空文件夹失败 ->{}, e->{}", file.getName(), e);
            }
        }
    }

    /**
     *
     * @Description: 创建文件
     * @param
     * @return
     */
    @SneakyThrows
    public static File createIfNotExists(final File file) {
        if (file == null) {
            return null;
        }
        if (file.exists()) {
            return file;
        }

        final File parent = file.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
        if (!file.createNewFile()) {
            logger.error("创建文件失败");
            return null;
        }
        return file;
    }


    public String getUploadResource(String fileName) {
        //返回读取指定资源的输入流
        InputStream is = this.getClass().getResourceAsStream("/files/" + fileName);
        //若文件已存在，则返回的filePath中含有"EXIST"，则不需再重写文件
        String filePath = createFile(fileName);
        //文件不存在，则创建流输入默认数据到新文件
        if (!filePath.contains("EXIST")) {
            File file = new File(filePath);
            inputStreamToFile(is, file);
            return filePath;
        }
        return filePath.substring(5);
    }

    public String createFile(String filename) {
        String path = System.getProperty("user.dir");
        //create folder
        String dirPath = path + File.separator + "uploadFiles";
        File dir = new File(dirPath);
        dir.mkdirs();
        //create file
        String filePath = dirPath + File.separator + filename;
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return filePath;
        }
        return "EXIST" + filePath;

    }

    public void inputStreamToFile(InputStream ins, File file) {
        OutputStream os = null;

        try {
            os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while ((bytesRead = ins.read(buffer, 0, 1024)) != -1) {
                os.write(buffer, 0, bytesRead);

            }
            os.close();
            ins.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        }

    }

}
